package siotwx.dao;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.entity.MeterDataBean;
import siotwx.entity.Readmeter;

public class MeterDao {
	
	
	public static List<Readmeter> getMeterData() {
		List<Map<String,String>> meterLastRead = getMeterLastRead();
		List<Readmeter> list=new ArrayList<>();
		for(Map<String, String> map:meterLastRead){
			Readmeter readmeter=new Readmeter();
			readmeterSeter(readmeter,map);
			list.add(readmeter);
		}
		return list;
	}
	//使用反射的方式设置obj的数据属性值
	private static void readmeterSeter(Readmeter readmeter, Map<String, String> map) {
		Field[] fields = readmeter.getClass().getDeclaredFields();
		for(Map.Entry<String, String> key:map.entrySet()){
			String value = key.getValue();
			String mapKey = key.getKey();
			for(Field field:fields){
				if (field.getName().toUpperCase().equals(mapKey.toUpperCase())) {
					field.setAccessible(true);
					try {
						field.set(readmeter, value);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	//获取指定电表的时间段内的读数数据
	/**
	 * 获取指定电表的一个月内的电量数据
	 * @author 周超 2018年3月7日 
	 * 
	 * @param DBMeterKID 指定的电表的标识符
	 * @return 返回指定的电表的一个月的一个月内的数据
	 */
	public static MeterDataBean getMeterTendencyD(String DBMeterKID){
		MeterDataBean res=new MeterDataBean("日用电量");

		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date(System.currentTimeMillis()-1000L*3600*24*60));
		String sql="SELECT"
				+ " MeterID DBMeterKID,"
				+ "ReadTime KReadTime,"
				+ "ThisRead KThisTimeRead,"
				+ "LastRead KLastTimeRead "
				+ "FROM  "
				+ "HD_ReadMeter "
				+ "WHERE MeterID = '" + DBMeterKID 
				+ "' and ReadTime>='"+date+"' "
				+ "ORDER BY ReadTime desc";
		
		List<HashMap<String, String>> theMeterRead = SQLServerDao.executeSqlWithResult(sql);
		if (theMeterRead==null||theMeterRead.size()==0) {
			return res;
		}
		
		//将读表记录按照月份进行分类
		List<List<Map<String,String>>> split = splitD(theMeterRead);
		//用于保存月份
		List<String> mouths=new ArrayList<>();
		//用于保存月消耗总电量
		List<String> meters=new ArrayList<>();
		
		for(List<Map<String, String>> mouth:split){
			mouths.add(mouth.get(0).get("KReadTime").substring(0,mouth.get(0).get("KReadTime").indexOf(":")-3));
			String v1=mouth.get(0).get("KThisTimeRead");
			String v2=mouth.get(mouth.size()-1).get("KLastTimeRead");
			BigDecimal b1 = new BigDecimal(v1);
			BigDecimal b2 = new BigDecimal(v2);
			
			
			meters.add(b1.subtract(b2).doubleValue()+"");
		}
		res.setMeters(meters);
		res.setTime(mouths);
		
		return res;
	}
	
	//获取指定电表的时间段内的读数数据
	/**
	 * 获取指定电表的一个月内的电量数据
	 * author 周超 2018年3月7日 
	 * 
	 * @param DBMeterKID 指定的电表的标识符
	 * @return 返回指定的电表的一个月的一个月内的数据
	 */
	public static MeterDataBean getMeterTendencyM(String DBMeterKID){
		MeterDataBean res=new MeterDataBean("月用电量");

		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date(System.currentTimeMillis()-1000L*3600*24*30*7));
		
		
		// 获取当前电表的全部读取电量信息 WHERE DBMeterKID = '" + kid
		String sql = "SELECT"
				+ " MeterID DBMeterKID,"
				+ "ReadTime KReadTime,"
				+ "ThisRead KThisTimeRead,"
				+ "LastRead KLastTimeRead "
				+ "FROM  "
				+ "HD_ReadMeter "  
				+ "WHERE MeterID = '" + DBMeterKID 
				+"' and ReadTime>='"+date+"' "
				+ "ORDER BY ReadTime desc";
		List<HashMap<String, String>> theMeterRead = SQLServerDao.executeSqlWithResult(sql);
		if (theMeterRead==null||theMeterRead.size()==0) {
			return res;
		}
		
		//将读表记录按照月份进行分类
		List<List<Map<String,String>>> split = splitM(theMeterRead);
		//用于保存月份
		List<String> mouths=new ArrayList<>();
		//用于保存月消耗总电量
		List<String> meters=new ArrayList<>();
		
		for(List<Map<String, String>> mouth:split){
			mouths.add(mouth.get(0).get("KReadTime").substring(0,mouth.get(0).get("KReadTime").lastIndexOf("-")));
			String v1=mouth.get(0).get("KThisTimeRead");
			String v2=mouth.get(mouth.size()-1).get("KLastTimeRead");
			BigDecimal b1 = new BigDecimal(v1);
			BigDecimal b2 = new BigDecimal(v2);
			
			System.out.println(b1.floatValue()+"   "+b2.floatValue());
			
			meters.add(b1.subtract(b2).doubleValue()+"");
			System.out.println(b1.subtract(b2).doubleValue()+"");
		}
		res.setMeters(meters);
		res.setTime(mouths);
		
		return res;
	}
	

	// 将读表记录按照月份分类
	private static List<List<Map<String, String>>> splitM(List<? extends Map<String, String>> meterRead) {
		List<List<Map<String, String>>> list = new ArrayList<>();
		for (Map<String, String> entity : meterRead) {
			
			boolean isSave = true;
			for (int i = 0; i < list.size(); i++) {
				List<Map<String, String>> t = list.get(i);
				if (isSameM(entity, t.get(0))) {
					if (entity!=null) {
						t.add(entity);
						isSave = false;
						break;
					}
				}
			}
			//之前没有保存新的记录，创建新的类别
			if (isSave) {
				//当分类数目达到六类要创建第七了的时候停止进行分类
				if (list.size()>=6) {
					break;
				}
				if (entity!=null) {
					List<Map<String, String>> t = new ArrayList<>();
					t.add(entity);
					list.add(t);
				}
			}
		}

		return list;
	}

	// 判断时间是否在一个日子份
	private static boolean isSameM(Map<String, String> entity, Map<String, String> entity2) {
		String e1 = entity.get("KReadTime");
		e1 = e1.substring(0, e1.lastIndexOf("-"));
		String e2 = entity2.get("KReadTime");
		e2 = e2.substring(0, e2.lastIndexOf("-"));
		if (e1.equals(e2)) {
			return true;
		}

		return false;
	}
	
	// 将读表记录按照日期分类
	private static List<List<Map<String, String>>> splitD(List<? extends Map<String, String>> meterRead) {
		List<List<Map<String, String>>> list = new ArrayList<>();
		for (Map<String, String> entity : meterRead) {
			
			boolean isSave = true;
			for (int i = 0; i < list.size(); i++) {
				List<Map<String, String>> t = list.get(i);
				if (isSameD(entity, t.get(0))) {
					if (entity!=null) {
						t.add(entity);
						isSave = false;
						break;
					}
				}
			}
			//之前没有保存新的记录，创建新的类别
			if (isSave) {
				//当分类数目达到30类要创建第31了的时候停止进行分类
				if (list.size()>=30) {
					break;
				}
				if (entity!=null) {
					List<Map<String, String>> t = new ArrayList<>();
					t.add(entity);
					list.add(t);
				}
			}
		}
		return list;
	}

	// 判断时间是否在一个日子份
	private static boolean isSameD(Map<String, String> entity, Map<String, String> entity2) {
		String e1 = entity.get("KReadTime");
		e1 = e1.substring(0, e1.indexOf(":")-3);
		String e2 = entity2.get("KReadTime");
		e2 = e2.substring(0, e2.indexOf(":")-3);
		if (e1.equals(e2)) {
			return true;
		}
		return false;
	}
	
	// 获取最新的读表记录
	private static List<Map<String, String>> getMeterLastRead() {
		// 暂时储存匹配结果
		List<Map<String, String>> temp = new ArrayList<>();

		// 获取所有的电表编号
		String sqlMeter = "SELECT ID DBMeterKID ,[No] KNum,ColectorNo DBCollectorNum,Location KLocation FROM HD_Meter";
		List<HashMap<String, String>> meters = SQLServerDao.executeSqlWithResult(sqlMeter);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date(System.currentTimeMillis() - 1000L * 3600 * 24 * 10));

		// 获取全部读表记录
		String sql = "SELECT " + "HD_ReadMeter.MeterID  DBMeterKID, " + "HD_Meter.ColectorNo DBCollectorNum, "
				+ "HD_Meter.Location KLocation, " + "HD_ReadMeter.MeterNo KNum, "
				+ "HD_ReadMeter.ThisRead KThisTimeRead, " + "HD_ReadMeter.ReadTime KReadTime " + "FROM  "
				+ "HD_ReadMeter LEFT JOIN HD_Meter ON HD_ReadMeter.MeterID=HD_Meter.ID "
				+ " where HD_ReadMeter.ReadTime>=" + date + "ORDER BY HD_ReadMeter.ReadTime desc";
		List<HashMap<String, String>> readHis = SQLServerDao.executeSqlWithResult(sql);

		// 获取当前电表的最新读表数据
		for (Map<String, String> meter : meters) {
			for (Map<String, String> his : readHis) {
				if (meter.get("DBMeterKID").equals(his.get("DBMeterKID"))) {
					temp.add(his);
					break;
				}
			}
		}

		// 处理时间格式
		for (int i = 0; i < temp.size(); i++) {
			String KReadTime = temp.get(i).get("KReadTime");
			int pos = KReadTime.lastIndexOf(":");
			KReadTime = KReadTime.substring(0, pos);
			temp.get(i).put("KReadTime", KReadTime);
		}

		// 添加没有的表
		for (HashMap<String, String> en : meters) {
			if (!isTheOne(temp, en)) {
				temp.add(en);
			}
		}

		temp.sort(new Comparator<Map<String, String>>() {

			@Override
			public int compare(Map<String, String> o1, Map<String, String> o2) {
				Integer v1 = Integer.valueOf(o1.get("DBCollectorNum"));
				Integer v2 = Integer.valueOf(o2.get("DBCollectorNum"));
				return v1 - v2;
			}
		});
		
		return temp;
	}
	private static boolean isTheOne(List<Map<String, String>> temp,Map<String, String> thisOne){
		for(Map<String, String> entry:temp){
			if (thisOne.get("DBMeterKID").equals(entry.get("DBMeterKID"))) {
				return true;
			}
		}
		
		return false;
	}
}
